const nodemailer = require('nodemailer');
const logger = require('./logger');

function MailServer(option) {
    if(!option) {
        throw new Error('config required');
    }
    this._host = option.host;
    this._user = option.user;
    this._pass = option.pass;
    this.init({});
}
MailServer.prototype = {
    init: function(option) {
        if(!this._smpt) {
            this._smpt = nodemailer.createTransport({
                host: this._host,
                port: 465,
                secure: true,
                auth: {
                    user: this._user,
                    pass: this._pass
                }
            });
        }
        this._subject = option.subject;
        this._from = option.from || `小柿饼系统邮件 <${this._user}>`;
        this.to = option.to;
    },
    /**
    * @param {string} server 邮件服务类型 default: smpt
    * @param {string} from 发送人
    * @param {string} to 接收人
    * @param {string} subject 主题
    * @param {string} html 内容
    */
    sendMail: function(option) {
        option = option || {};
        const server = option.server || 'smpt';
        return new Promise((resolve, reject) => {
            this['_' + server].sendMail({
                from: option.from || this._from,
                to: option.to || this._to,
                subject: option.subject || this._subject,
                attachments: option.attachments,
                html: option.html
            }, (err, res) => {
                if(err) {
                    logger.error(err);
                    reject(err);
                }
                resolve(res);
            });
        });
    },
};
module.exports = MailServer;
